#pragma once

#include <string>
#include <iostream>
#include "init.hpp"

class Task
{
public:
    Task()
    {

    }

    Task(int sockfd, const std::string& client_ip, const uint16_t& client_port)
        : _sockfd(sockfd)
        , _client_ip(client_ip)
        , _client_port(client_port)
        {}

    void run()
    {
        char inbuffer[4096];

        // 读取数据
        ssize_t n = read(_sockfd, inbuffer, sizeof(inbuffer) - 1);
        if(n > 0)
        {
            inbuffer[n] = '\0';
            std::cout << "client[" << _client_ip << ":" << _client_port << "] Key# " << inbuffer << std::endl;
            init t;
            std::string outbuffer = t.translation(inbuffer);

            if(write(_sockfd, outbuffer.c_str(), outbuffer.size()) < 0)
            {
                lg(Warning, "write error, errno: %d, error string: %s", errno, strerror(errno));
            }
        }
        else if(n == 0)
        {
            lg(Info, "client %s : %d quit", _client_ip.c_str(), _client_port);
        }

        close(_sockfd);
    }

    void operator()()
    {
        run();
    }

private:
    int _sockfd;
    std::string _client_ip;
    uint16_t _client_port;

};